/*
 * @Description: 条目检测 - 完整性检测
 * @Author: Rfan
 * @Date: 2022-10-10 14:19:09
 * @LastEditTime: 2022-10-22 17:23:05
 */

import { forwardRef, Key, Ref, useEffect, useImperativeHandle, useState } from 'react';
import { Checkbox, Table, Tabs, Typography } from 'antd';
import classnames from 'classnames/bind';
import { jsonClone } from '@/utils';
import { editItemById, insertItem, selectItemByKey } from '@/utils/list';
import { useAddPlanDialogContext } from '../../../../contexts/AddPlanDialogContext';
import {
  CheckProps,
  EnumCheckContentType,
  EnumIntegralityRuleType
} from '../../../../../../../dictionaries';
import Continuity from './components/Continuity';
import type { ILevel } from '@/interfaces/archiveType';
import type { IPropsRule, IPropsRuleWithSetting } from '@/view/system/ArchivesDetection/interface';
import styles from '../../../../styles/entryPanes.module.scss';

const cx = classnames.bind(styles);
const { TabPane } = Tabs;
const { Column } = Table;

const integrityInitRules = [
  {
    ruleType: EnumIntegralityRuleType.ItemFieldExist,
    ruleValid: false
  },
  {
    ruleType: EnumIntegralityRuleType.ItemFieldValueRequired,
    ruleValid: false
  },
  {
    ruleType: EnumIntegralityRuleType.ItemFieldValueContinuity,
    ruleValid: false,
    rule: {
      contentType: EnumCheckContentType.Regular,
      content: ''
    }
  }
];

// 字段规则各层级字段规则类型
export interface IIntegrityFieldLevelRule {
  key?: Key;
  field: string;
  rules: (IPropsRule<EnumIntegralityRuleType> | IPropsRuleWithSetting<EnumIntegralityRuleType>)[];
}

// 完整性字段规则类型
export interface IIntegrityFieldRules {
  level: number;
  levelName: string;
  rules: IIntegrityFieldLevelRule[];
}

// 条目完整性完整类型
export interface IIntegrityFullRules {
  ruleType: CheckProps.Integrity;
  rules: IIntegrityFieldRules[];
}

const EntryIntegrityCheck = forwardRef((props: any, ref: Ref<unknown>) => {
  const { levelFieldList, combineLeveAndRulesInfo } = useAddPlanDialogContext();

  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState<string>('');
  // 表格内容
  const [integrityTable, setIntegrityTable] = useState<IIntegrityFieldLevelRule[]>([]);
  // excel列与元数据字段关系
  const [colRelation, setColRelation] = useState<IIntegrityFieldRules[]>([]);

  useImperativeHandle(ref, () => ({
    save: () => {
      const levelRules: IIntegrityFieldRules[] = saveTableForm();
      const fullRules: IIntegrityFullRules = {
        ruleType: CheckProps.Integrity,
        rules: levelRules
      };
      return fullRules;
    }
  }));

  useEffect(() => {
    if (levelFieldList.length > 0) {
      setCurrentTab(levelFieldList[0].level + '');
    }
  }, [levelFieldList]);

  useEffect(() => {
    if (currentTab && levelFieldList.length > 0) {
      const numCurTab = parseInt(currentTab, 10);
      const currentData = colRelation.find((item: any) => item.level === numCurTab);
      console.log('currentData', currentData);
      setIntegrityTable(
        currentData?.rules ||
          combineLeveAndRulesInfo(CheckProps.Integrity, numCurTab, integrityInitRules)
      );
    }
  }, [currentTab, levelFieldList]);

  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    saveTableForm();
    setCurrentTab(key);
  };

  /**
   * @description: 保存当前层级填入字段
   */
  const saveTableForm = () => {
    const newState: IIntegrityFieldRules[] = jsonClone(colRelation);
    const currentLevel: ILevel =
      selectItemByKey(parseInt(currentTab, 10), levelFieldList, 'level') || {};
    const { level, levelName } = currentLevel;
    if (newState.length > 0) {
      let flag: boolean = false;
      newState.forEach((item) => {
        if (item.level === level) {
          item.rules = integrityTable;
          flag = true;
        }
      });
      // 如果循环完没有当前层级
      if (!flag) {
        newState.push({
          level,
          levelName,
          rules: integrityTable
        });
      }
    } else {
      newState.push({
        level,
        levelName,
        rules: integrityTable
      });
    }
    setColRelation(newState);
    return newState;
  };

  /**
   * @description: 保存单元格操作选择的内容
   * @param {Key} key 条目key
   * @param {number} type 检测类型
   * @param {any} data 修改后的检测规则
   */
  const saveRules = (key: Key, type: number, data: any) => {
    // 修改的条目
    const selectData = selectItemByKey(key, integrityTable, 'key');
    const rules = selectItemByKey(type, selectData.rules, 'ruleType')
      ? editItemById(type, data, selectData.rules, 'ruleType')
      : insertItem(data, selectData.rules);
    setIntegrityTable((state) => editItemById(key, { ...selectData, rules }, state, 'key'));
  };

  /**
   * @description: 根据类型获取复选框状态
   * @param {EnumIntegralityRuleType} type 完整性规则类型
   * @param {any} info 当前条目
   * @return {boolean} 复选框状态
   */
  const getCheckboxStatus = (type: EnumIntegralityRuleType, info: any): boolean => {
    const selectData = selectItemByKey(info.key, integrityTable, 'key');
    const rules = selectItemByKey(type, selectData.rules, 'ruleType');
    return rules?.ruleValid;
  };

  /**
   * @description: 根据类型设置复选框状态
   * @param {Boolean} status 当前状态
   * @param {EnumIntegralityRuleType} type 完整性规则类型
   * @param {any} info 当前条目
   */
  const saveCheckboxStatus = (status: Boolean, type: EnumIntegralityRuleType, info: any) => {
    const data = {
      ruleType: type,
      ruleValid: status
    };

    saveRules(info.key, type, data);
  };

  const operations = {
    left: (
      <Typography.Text className={cx('auth-tab-title')} strong>
        元数据设置
      </Typography.Text>
    )
  };

  return (
    <>
      <Tabs activeKey={currentTab} tabBarExtraContent={operations} onChange={tabsChange}>
        {levelFieldList.map((level: ILevel) => (
          <TabPane tab={level.levelName} key={level.level}>
            <Table dataSource={integrityTable} size="small" pagination={false} bordered>
              <Column title="元数据项" dataIndex="field" key="field" align="center" />
              <Column
                title="是否存在"
                dataIndex="exist"
                key="exist"
                align="center"
                render={(_val, record: any) => (
                  <Checkbox
                    checked={getCheckboxStatus(EnumIntegralityRuleType.ItemFieldExist, record)}
                    onChange={(evt) => {
                      saveCheckboxStatus(
                        evt.target.checked,
                        EnumIntegralityRuleType.ItemFieldExist,
                        record
                      );
                    }}
                  />
                )}
              />
              <Column
                title="必填项"
                dataIndex="required"
                key="required"
                align="center"
                render={(_val, record: any) => (
                  <Checkbox
                    checked={getCheckboxStatus(
                      EnumIntegralityRuleType.ItemFieldValueRequired,
                      record
                    )}
                    onChange={(evt) => {
                      saveCheckboxStatus(
                        evt.target.checked,
                        EnumIntegralityRuleType.ItemFieldValueRequired,
                        record
                      );
                    }}
                  />
                )}
              />
              <Column
                title="连续性"
                dataIndex="name"
                key="name"
                align="center"
                render={(_val, record: any) => <Continuity data={record} onChange={saveRules} />}
              />
            </Table>
          </TabPane>
        ))}
      </Tabs>
    </>
  );
});

export default EntryIntegrityCheck;
